import { Model, Effect } from 'dva';
import { Reducer } from 'redux';
import { BiStatus } from '@/common/type/BiStatus';
import { queryList, removeList, addList, updateList } from './service';

export interface Advertise {
  id: number;
  name: string;
  pic: string;
  startTime: string;
  endTime: string;
  status: BiStatus;
  clickCount: number;
  url: string;
}

export interface StateType {
  list: Advertise[];
}

export interface ModelType extends Model {
  namespace: 'advertise';
  state: StateType;
  effects: {
    fetch: Effect;
    remove: Effect;
    submit: Effect;
    update: Effect;
  };
  reducers: {
    queryList: Reducer<StateType>;
  };
}

const model: ModelType = {
  namespace: 'advertise',
  state: {
    list: [],
  },

  reducers: {
    queryList(state, action) {
      return {
        ...state,
        list: action.payload,
      };
    },
  },

  effects: {
    *fetch({ _payload }, { call, put }) {
      const response = yield call(queryList);
      yield put({
        type: 'queryList',
        payload: Array.isArray(response) ? response : [],
      });
    },
    *remove({ id }, { call, put }) {
      const response = yield call(removeList, id);
      if (response) {
        yield put({
          type: 'fetch',
        });
      }
    },
    *submit({ payload, callback }, { call }) {
      const formData = new FormData();
      for (const key of Object.keys(payload)) {
        if (key !== 'pic') {
          formData.append(key, payload[key]);
        } else {
          formData.append(
            'picFile',
            payload[key][0].originFileObj,
            payload[key][0].originFileObj.name,
          );
        }
      }
      const response = yield call(addList, formData);
      if (response && callback) {
        callback();
      }
    },
    *update({ payload }, { call, put }) {
      console.log('asd');
      const response = yield call(updateList, payload);
      if (response) {
        yield put({
          type: 'fetch',
        });
      }
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname.startsWith('/marketing/adList')) {
          dispatch({
            type: 'fetch',
          });
        }
      });
    },
  },
};

export default model;
